package com.wbcs.system.dataimport.thread;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wbcs.config.Config;
import com.wbcs.config.resource.dataimport.configbean.AbsDataImportConfigBean;
import com.wbcs.exception.WbcsDataImportException;
import com.wbcs.system.assistant.DataImportAssistant;
import com.wbcs.system.dataimport.DataImportItem;
import com.wbcs.util.Consts_Private;
import com.wbcs.util.FileLockTools;
import com.wbcs.util.Tools;

public class TimingDataImportThread extends AbsDataImportThread
{
    private static Log log=LogFactory.getLog(TimingDataImportThread.class);

    private final static TimingDataImportThread instance=new TimingDataImportThread();

    private TimingDataImportThread()
    {}

    public static TimingDataImportThread getInstance()
    {
        return instance;
    }

    @Override
	public void run()
    {
        while(RUNNING_FLAG)
        {
            Map<String,List<AbsDataImportConfigBean>> mAutoDetectedDataImportBeans=Config
                    .getInstance().getMAutoDetectedDataImportBeans();
            if(mAutoDetectedDataImportBeans!=null&&mAutoDetectedDataImportBeans.size()>0)
            {
                String lockfile;
                for(Entry<String,List<AbsDataImportConfigBean>> entryTmp:mAutoDetectedDataImportBeans
                        .entrySet())
                {
                    String filepath=entryTmp.getKey();
                    File f=new File(filepath);
                    if(!f.exists()||!f.isDirectory())
                    {
                        log.warn("数据导入项的监控路径"+filepath+"不存在或不是目录，无法导入其上的数据文件");
                        continue;
                    }
                    lockfile=Tools.standardFilePath(filepath+"\\"
                            +Consts_Private.DATAIMPORT_LOCKFILENAME);
                    Object lockresource=FileLockTools.lock(lockfile,10,5);
                    if(lockresource==null)
                    {
                        log.debug("定时监控线程没有取到文件锁"+lockfile+"，本周期没有对此目录进行监控");
                        continue;
                    }
                    try
                    {
                        File[] filesArr=f.listFiles();
                        if(filesArr==null||filesArr.length==0) continue;
                        for(int i=0;i<filesArr.length;i++)
                        {
                            if(filesArr[i].isDirectory()) continue;
                            if(Consts_Private.DATAIMPORT_LOCKFILENAME.equalsIgnoreCase(filesArr[i].getName()))
                                continue;
                            doImportData(filesArr[i],entryTmp.getValue());
                        }
                    }catch(Exception e)
                    {
                        log.error("监控并导入路径"+filepath+"下的数据文件失败",e);
                    }finally
                    {
                        FileLockTools.unlock(lockfile,lockresource);
                    }
                }
            }
            try
            {
                int runcycle=Config.getInstance().getSystemConfigValue("dataimport-autodetect-interval",30);
                if(runcycle<=0) runcycle=30;
                Thread.sleep(runcycle*1000);
            }catch(InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }

    private void doImportData(File file,List<AbsDataImportConfigBean> lstDataImportBeans)
    {
        if(lstDataImportBeans==null||lstDataImportBeans.size()==0) return;
        List<DataImportItem> lstResults=new ArrayList<DataImportItem>();
        try
        {
            String[] strArrTmp=DataImportAssistant.getInstance().getRealFileNameAndImportType(file.getName());
            DataImportItem diitem;
            for(AbsDataImportConfigBean dibeanTmp:lstDataImportBeans)
            {
                if(dibeanTmp.isMatch(strArrTmp[0]))
                {
                    diitem=new DataImportItem(dibeanTmp,file);
                    diitem.setDynimportype(strArrTmp[1]);
                    lstResults.add(diitem);
                }
            }
            if(lstResults.size()==0)
            {
                log.warn("数据文件"+file.getAbsolutePath()+"没有对应的数据导入项，不会对其进行导入");
            }else
            {
                for(DataImportItem diiTmp:lstResults)
                {
                    diiTmp.doImportData();
                }
            }
        }catch(Exception e)
        {
            throw new WbcsDataImportException("导入数据文件"+file.getPath()+"失败",e);
        }finally
        {
           DataImportItem.backupOrDeleteDataFile(file);
        }
    }
}
